from datetime import datetime
from flask import Flask
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields,validate

app = Flask(__name__)

ma = Marshmallow()
ma.init_app(app)

class UserSchema(Schema):
    name = fields.String(validate=validate.Length(min=1))
    permission = fields.String(required=True, validate=validate.OneOf(["read", "write", "admin"]))
    age = fields.Integer(required=True,error_messages={"required":"age必须填写!"}, validate=validate.Range(min=18, max=40,error="age超出范围！age >= 18 and age <=40"))

@app.route("/")
def index():
    # user_data = {"name": "小明", "email": "xiaoming@qq.com"}
    """
    marshmallow.exceptions.ValidationError: {'email': ['Unknown field.']}
    """

    user_data = {"name": "小明"} # 通过
    """
    age = fields.Integer(validate=validate.Range(min=18, max=40))
    在其他几个字段没有被设置为required=True的时候，验证是通过的
    """

    user_data = {"name": "小明"} # 报错
    """
    # age = fields.Integer(required=True, validate=validate.Range(min=18, max=40))
    marshmallow.exceptions.ValidationError: {'age': ['Missing data for required field.']}
    """

    user_data = {"name": "小明"}  # 报错
    """
    # age = fields.Integer(required=True,error_messages={"required":"age必须填写!"}, validate=validate.Range(min=18, max=40))
    marshmallow.exceptions.ValidationError: {'age': ['age必须填写!']}
    """

    user_data = {"name": "小明","age":16}  # 报错
    """
    # age = fields.Integer(required=True,error_messages={"required":"age必须填写!"}, validate=validate.Range(min=18, max=40,error="age超出范围！age >= 18 and age <=40"))
    marshmallow.exceptions.ValidationError: {'age': ['age超出范围！age >= 18 and age <=40']}
    """

    user_data = {"name": "小明", "age": 20,"permission":"xiaoming"}  # 报错
    """
    # permission = fields.String(required=True, validate=validate.OneOf(["read", "write", "admin"]))
    marshmallow.exceptions.ValidationError: {'permission': ['Must be one of: read, write, admin.']}
    """

    user_data = {"name": "小明", "age": 20}  # 报错
    us = UserSchema()
    # result = us.load(user_data)
    result = us.load(user_data,partial=True) # 开发中会存在一些模型的数据在添加时是必填，但是在更新/修改时，不需要必填的
    print(result)

    return "hello"

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port=5999)